package babo.cd.physicalexperiment.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;

import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.style.PictureCropParameterStyle;
import com.luck.picture.lib.style.PictureParameterStyle;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;

import java.io.File;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import babo.cd.physicalexperiment.BaseActivity;
import babo.cd.physicalexperiment.MainActivity;
import babo.cd.physicalexperiment.R;
import babo.cd.physicalexperiment.app.MyApplication;
import babo.cd.physicalexperiment.bean.JustDataBean;
import babo.cd.physicalexperiment.bean.UserInfoBean;
import babo.cd.physicalexperiment.data.UserInfo;
import babo.cd.physicalexperiment.databinding.UpdateuserinfoActivityBinding;
import babo.cd.physicalexperiment.utils.GlideEngine;
import babo.cd.physicalexperiment.utils.OKCallback;
import babo.cd.physicalexperiment.utils.OkUtils;
import babo.cd.physicalexperiment.utils.Out;
import babo.cd.physicalexperiment.utils.URLS;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class UploadBaseInfoActivity extends BaseActivity {
  UpdateuserinfoActivityBinding binding;
  private int sex=1;
    File tempFile;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode== KeyEvent.KEYCODE_BACK){
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }


    @Override
    protected View bindView() {
        binding=UpdateuserinfoActivityBinding.inflate(getLayoutInflater());
        return binding.getRoot();
    }

    @Override
    protected void initView() {

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, 123);
            }
        }
    }

    @Override
    public void setListener() {
        super.setListener();
        binding.llHead.setOnClickListener(this);
        binding.rlBoy.setOnClickListener(this);
        binding.rlGirl.setOnClickListener(this);
        binding.btnSave.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        if (v==binding.rlBoy){
            binding.ivSexBoy.setBackgroundResource(R.mipmap.yixuanzhe);
            binding.ivSexGirl.setBackgroundResource(R.mipmap.weixuanzhe);
            sex=1;
        }
        if (v==binding.rlGirl){
            binding.ivSexBoy.setBackgroundResource(R.mipmap.weixuanzhe);
            binding.ivSexGirl.setBackgroundResource(R.mipmap.yixuanzhe);
            sex=0;
        }
        if (v==binding.llHead){
            doSelectImg();
        }
        if (v==binding.btnSave){
            if (tempFile==null){
                Out.toast(context,"请上传头像！");
                return;
            }
            if (TextUtils.isEmpty(binding.edname.getText().toString().trim())){
                Out.toast(context,"请输入姓名！");
                return;
            }
            post3(URLS.uploadImage,new OKCallback(context){
                @Override
                public void Sucess(String str) {
                    super.Sucess(str);
                    try {
                        JustDataBean justDataBean=gson.fromJson(str,JustDataBean.class);
                        Out.out("上传回来的头像："+justDataBean.getData());
                        uploadUsrInfo(justDataBean.getData());
                    }catch (Exception ex){
                        ex.printStackTrace();
                    }
                }
            },null,tempFile,null,null,UserInfo.JsessionId);

        }
    }

    private void uploadUsrInfo(String data) {
        LinkedHashMap hashMap=new LinkedHashMap();
        hashMap.put("id",UserInfo.userId);
        hashMap.put("avatar",data);
        hashMap.put("name",binding.edname.getText().toString().trim());
        OkUtils.performByJsonArray(context,URLS.uploadUserInfo,hashMap,2,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                getUserBaseInfo();
            }
        });
    }

    private void getUserBaseInfo() {

        OkUtils.GetOk(URLS.getUserInfo,new OKCallback(context){
            @Override
            public void Sucess(String str) {
                super.Sucess(str);
                Out.out("获取用户返回："+str);
                UserInfoBean userInfoBean=gson.fromJson(str,UserInfoBean.class);
                MyApplication.getInstance().setUserBaseInfo(userInfoBean.getData());
                if (TextUtils.isEmpty(userInfoBean.getData().getName())){
                    hd.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            goToNextActivity(UploadBaseInfoActivity.class);
                            finish();
                        }
                    },1000);

                }else{
                    hd.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            goToNextActivity(MainActivity.class);
                            finish();
                        }
                    },1500);

                }


            }
        });
    }

    private void doSelectImg() {
        PictureParameterStyle mPictureParameterStyle = new PictureParameterStyle();
// 是否改变状态栏字体颜色(黑白切换)
        mPictureParameterStyle.isChangeStatusBarFontColor = false;
// 是否开启右下角已完成(0/9)风格
        mPictureParameterStyle.isOpenCompletedNumStyle = false;
// 是否开启类似QQ相册带数字选择风格
        mPictureParameterStyle.isOpenCheckNumStyle = true;
// 相册状态栏背景色
        mPictureParameterStyle.pictureStatusBarColor = Color.parseColor("#393a3e");
// 相册列表标题栏背景色
        mPictureParameterStyle.pictureTitleBarBackgroundColor = Color.parseColor("#393a3e");
// 相册列表标题栏右侧上拉箭头
        mPictureParameterStyle.pictureTitleUpResId = R.drawable.picture_icon_arrow_up;
// 相册列表标题栏右侧下拉箭头
        mPictureParameterStyle.pictureTitleDownResId = R.drawable.picture_icon_arrow_down;
// 相册文件夹列表选中圆点
        mPictureParameterStyle.pictureFolderCheckedDotStyle = R.drawable.picture_orange_oval;
// 相册返回箭头
        mPictureParameterStyle.pictureLeftBackIcon = R.drawable.picture_icon_back;
// 标题栏字体颜色
        mPictureParameterStyle.pictureTitleTextColor = ContextCompat.getColor(this, R.color.picture_color_white);
// 相册右侧取消按钮字体颜色
        mPictureParameterStyle.pictureCancelTextColor = ContextCompat.getColor(this, R.color.picture_color_white);
// 相册列表勾选图片样式
        mPictureParameterStyle.pictureCheckedStyle = R.drawable.picture_checkbox_selector;
// 选择相册目录背景样式

// 相册列表底部背景色
        mPictureParameterStyle.pictureBottomBgColor = ContextCompat.getColor(this, R.color.picture_color_fa);
// 已选数量圆点背景样式
        mPictureParameterStyle.pictureCheckNumBgStyle = R.drawable.picture_num_oval;
// 相册列表底下预览文字色值(预览按钮可点击时的色值)
        mPictureParameterStyle.picturePreviewTextColor = ContextCompat.getColor(this, R.color.picture_color_fa632d);
// 相册列表底下不可预览文字色值(预览按钮不可点击时的色值)
        mPictureParameterStyle.pictureUnPreviewTextColor = ContextCompat.getColor(this, R.color.picture_color_9b);
// 相册列表已完成色值(已完成 可点击色值)
        mPictureParameterStyle.pictureCompleteTextColor = ContextCompat.getColor(this, R.color.picture_color_fa632d);
// 相册列表未完成色值(请选择 不可点击色值)
        mPictureParameterStyle.pictureUnCompleteTextColor = ContextCompat.getColor(this, R.color.picture_color_9b);
// 预览界面底部背景色
        mPictureParameterStyle.picturePreviewBottomBgColor = ContextCompat.getColor(this, R.color.picture_color_grey_3e);
// 外部预览界面删除按钮样式
        mPictureParameterStyle.pictureExternalPreviewDeleteStyle = R.drawable.picture_icon_delete;
// 外部预览界面是否显示删除按钮
        mPictureParameterStyle.pictureExternalPreviewGonePreviewDelete = true;
// 相册右侧按钮背景样式,只针对isWeChatStyle 为true时有效果
        mPictureParameterStyle.pictureUnCompleteBackgroundStyle = R.drawable.picture_send_button_default_bg;
// 相册右侧按钮可点击背景样式,只针对isWeChatStyle 为true时有效果
        mPictureParameterStyle.pictureCompleteBackgroundStyle = R.drawable.picture_send_button_bg;

// 以下设置如果用不上则不要设置，使用默认即可
// 自定义相册右侧文本内容设置
        mPictureParameterStyle.pictureRightDefaultText = "";
// 自定义相册未完成文本内容
        mPictureParameterStyle.pictureUnCompleteText = "";
// 完成文案是否采用(%1$d/%2$d)的字符串，只允许两个占位符哟
        mPictureParameterStyle.isCompleteReplaceNum = true;
// 自定义相册完成文本内容
        mPictureParameterStyle.pictureCompleteText = "";
// 自定义相册列表不可预览文字
        mPictureParameterStyle.pictureUnPreviewText = "";
// 自定义相册列表预览文字
        mPictureParameterStyle.picturePreviewText = "";
// 自定义相册标题字体大小
        mPictureParameterStyle.pictureTitleTextSize = 18;
// 自定义相册右侧文字大小
        mPictureParameterStyle.pictureRightTextSize = 14;
// 自定义相册预览文字大小
        mPictureParameterStyle.picturePreviewTextSize = 14;
// 自定义相册完成文字大小
        mPictureParameterStyle.pictureCompleteTextSize = 14;
// 自定义原图文字大小
        mPictureParameterStyle.pictureOriginalTextSize = 14;

// 裁剪主题
        PictureCropParameterStyle mCropParameterStyle = new PictureCropParameterStyle(
                ContextCompat.getColor(context, R.color.picture_color_grey),
                ContextCompat.getColor(context, R.color.picture_color_grey),
                ContextCompat.getColor(context, R.color.picture_color_white),
                mPictureParameterStyle.isChangeStatusBarFontColor);

        // 相册启动退出动画
        PictureWindowAnimationStyle windowAnimationStyle = new PictureWindowAnimationStyle();
        windowAnimationStyle.ofAllAnimation(R.anim.picture_anim_up_in, R.anim.picture_anim_down_out);
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine()) // 请参考Demo GlideEngine.java
                .maxSelectNum(1)
                .enableCrop(true)
                .setPictureStyle(mPictureParameterStyle)
                .selectionMode(PictureConfig.SINGLE)//
                .withAspectRatio(1, 1)
                .compress(true)// 是否压缩
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void loadData() {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    Glide.with(context).load(selectList.get(0).getCompressPath()).into(binding.ivhead);
                    tempFile=new File(selectList.get(0).getCompressPath());
                    break;

            }
        }
    }

    public static void post3(String address, okhttp3.Callback callback, Map<String, String> map, File mfile, File mfile2, File mfile3, String token) {

        address=URLS.HTTPHEAD+address;
        OkHttpClient client = new OkHttpClient();
        MultipartBody.Builder builder = new MultipartBody.Builder();
        if (map != null) {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                builder.addFormDataPart(entry.getKey(), entry.getValue());
            }
        }


        if (mfile != null) {


            String TYPE = "application/octet-stream";
            RequestBody fileBody = RequestBody.create(MediaType.parse(TYPE), mfile);
            RequestBody requestBody = builder
                    .setType(MultipartBody.FORM)
                    .addFormDataPart("image ", mfile.getName(), fileBody)
                    .build();
            Request request = new Request.Builder()
                    .url(address)
                    .post(requestBody)
                    .addHeader("Cookie", "JSESSIONID="+ UserInfo.JsessionId)
                    .build();
            client.newCall(request).enqueue(callback);
            Out.out("开始网络请求没111=="+address);

        } else {
//            Log.d(TAG, "post3: 文件不存在");
//            RequestBody requestBody = builder
//                    .setType(MultipartBody.FORM)
//                    .build();
//            Request request = new Request.Builder()
//                    .url(address)
//                    .post(requestBody)
//                    .addHeader("Cookie", "JSESSIONID="+ UserInfo.JsessionId)
//                    .build();
//            client.newCall(request).enqueue(callback);
            Out.out("开始网络请求没：000---"+address);
        }

    }
}
